<template>
    <el-button
      type="primary"
      plain
      icon="el-icon-document"
      size="mini"
      @click="handleGeneratePDF"
    >生成PDF</el-button>
  </template>
  
  <script>
  import html2canvas from 'html2canvas';
  import jsPDF from 'jspdf';
  import QRCode from 'qrcodejs2';
  
  export default {
    name: 'GeneratePDF',
    props: {
      // 头部配置信息
      headerInfo: {
        type: Object,
        required: true,
        default: () => ({
          deliveryNo: '',
          businessNo: '',
          sender: '',
          senderPhone: '',
          receiver: '',
          receiverPhone: '',
          deliveryAddress: '',
          printTime: '',
          printer: ''
        })
      },
      // 表格数据
      tableData: {
        type: Array,
        required: true,
        default: () => []
      },
      records:{
        type: Boolean,
      },
      // 是否显示批次号
      isBatch: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        qrCodeUrl: '',
        qrCodeInstance: null
      }
    },
    methods: {
      // 生成二维码
      async generateQRCode() {
        return new Promise((resolve, reject) => {
          try {
            // 清理之前的实例
            if (this.qrCodeInstance) {
              this.qrCodeInstance.clear();
            }
  
            // 创建临时容器
            const qrContainer = document.createElement('div');
            qrContainer.id = 'tempQrCode';
            document.body.appendChild(qrContainer);
  
            // 创建新的二维码实例
            this.qrCodeInstance = new QRCode(qrContainer, {
              text: this.headerInfo.no || 'test',
              width: 100,
              height: 100,
              colorDark: '#000000',
              colorLight: '#ffffff',
              correctLevel: QRCode.CorrectLevel.H
            });
  
            // 等待二维码生成
            setTimeout(() => {
              try {
                const qrImage = qrContainer.querySelector('img');
                if (qrImage && qrImage.src) {
                  this.qrCodeUrl = qrImage.src;
                  // 清理临时容器
                  document.body.removeChild(qrContainer);
                  resolve();
                } else {
                  throw new Error('二维码图片未生成');
                }
              } catch (err) {
                reject(err);
              }
            }, 100);
          } catch (error) {
            reject(error);
          }
        });
      },
  
      /** 生成PDF */
      async handleGeneratePDF() {
        if(this.tableData.length === 0) {
          this.$message.warning('没有数据可供生成PDF');
          return;
        }
  
        try {
          // 显示加载提示
          const loading = this.$loading({
            lock: true,
            text: '正在生成PDF...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
  
          // 先生成二维码
          await this.generateQRCode();
          
          // 确保二维码已经生成
          if (!this.qrCodeUrl) {
            throw new Error('二维码未生成');
          }
  
          // 创建PDF文档
          const pdf = new jsPDF({
            orientation: 'portrait',
            unit: 'mm',
            format: 'a4',
            compress: true
          });
  
          // 每页显示的行数
          const rowsPerPage = 23;
          // 计算总页数
          const totalPages = Math.ceil(this.tableData.length / rowsPerPage);
  
          // 遍历每一页
          for (let pageNum = 0; pageNum < totalPages; pageNum++) {
            // 创建打印容器
            const printContainer = document.createElement('div');
            printContainer.id = 'print-container';
            printContainer.style.cssText = `
              position: fixed;
              left: -9999px;
              top: -9999px;
              width: 794px;
              background: white;
              padding: 20px 40px;
              font-family: SimSun, serif;
              box-sizing: border-box;
              font-size: 12px;
              line-height: 1.5;
            `;
            document.body.appendChild(printContainer);
  
            // 获取当前页的数据
            const startIndex = pageNum * rowsPerPage;
            const endIndex = Math.min(startIndex + rowsPerPage, this.tableData.length);
            const currentPageData = this.tableData.slice(startIndex, endIndex);
  
            // 构建PDF内容
            printContainer.innerHTML = `
              <div style="position: relative;">
                ${pageNum === 0 ? `
                <h2 style="text-align: center; font-size: 16px; margin: 0 0 15px 0; font-weight: normal;">${this.headerInfo.billTitle}</h2>
                
                <!-- 头部信息区域 -->
                <div style="margin-bottom: 15px; position: relative;">
                  <!-- 左侧信息 -->
                  <div style="width: 65%;">
                    <div style="margin-bottom: 5px;">
                      <span style="display: inline-block; min-width: 200px;">配送单号：${this.headerInfo.no || ''}</span>
                    </div>
                    <div style="margin-bottom: 5px;">
                      <div style="display: inline-block; min-width: 200px;">发货人：${this.headerInfo.sendName || ''}</div>
                    </div>
                    <div style="margin-bottom: 5px;">
                      <span style="display: inline-block; min-width: 200px;">发货电话：${this.headerInfo.sendPhone || ''}</span>
                    </div>
                    <div style="margin-bottom: 5px;">
                      <div style="display: inline-block;">收货人：${this.headerInfo.contactPersonName || ''}</div>
                    </div>
                    <div style="margin-bottom: 5px;">
                      <span style="display: inline-block; min-width: 200px;">收货电话：${this.headerInfo.contactPersonPhone || ''}</span>
                    </div>
                    <div>收货地址：${this.headerInfo.addressName || ''}</div>
                  </div>

                  <!-- 右侧信息 -->
                  <div style="position: absolute; top: 0; right: 100px; width: 35%; text-align: left;">
                    <div style="margin-bottom: 5px;">业务单号：${this.headerInfo.no || ''}</div>
                    <div style="margin-bottom: 5px;">分拣位置：${this.headerInfo.stockName || ''}</div>
                    <div style="margin-bottom: 5px;">仓库名称：${this.headerInfo.stockName || ''}</div>
                    <div style="margin-bottom: 5px;">打印日期：${this.headerInfo.printTime || ''}</div>
                    <div>打印人：${this.headerInfo.sendName || ''}</div>
                  </div>

                  <!-- 二维码 -->
                  <div style="position: absolute; top: -10px; right: 10px; width: 85px; height: 85px;">
                    <img src="${this.qrCodeUrl}" style="width: 100%; height: 100%;" />
                  </div>
                </div>
                ` : '<div style="margin-bottom: 10px;"></div>'}

                <!-- 表格部分 -->
                <table style="width: 100%; border-collapse: collapse; table-layout: fixed;">
                  <thead>
                    <tr>
                      <th style="width: 40px; border: 0.2px solid #666; padding: 4px; text-align: center; font-weight: normal;">行号</th>
                      <th style="width: 180px; border: 0.2px solid #666; padding: 4px; text-align: center; font-weight: normal;">物料编号</th>
                      <th style="border: 0.2px solid #666; padding: 4px; text-align: center; font-weight: normal;">物料名称</th>
                      <th style="width: 80px; border: 0.2px solid #666; padding: 4px; text-align: center; font-weight: normal;">需求数量</th>
                      ${this.isBatch ? `<th style="width: 80px; border: 0.2px solid #666; padding: 4px; text-align: center; font-weight: normal;">批次号</th>` : ''}
                      <th style="width: 80px; border: 0.2px solid #666; padding: 4px; text-align: center; font-weight: normal;">实发数量</th>
                      <th style="width: 60px; border: 0.2px solid #666; padding: 4px; text-align: center; font-weight: normal;">物料单位</th>
                    </tr>
                  </thead>
                  <tbody>
                    ${currentPageData.map((item, index) => `
                      <tr>
                        <td style="border: 0.2px solid #666; padding: 4px; text-align: center;">${startIndex + index + 1}.</td>
                        <td style="border: 0.2px solid #666; padding: 4px; text-align: left; word-break: break-all;">${item.productNo || ''}</td>
                        <td style="border: 0.2px solid #666; padding: 4px; text-align: left;">${item.productName || ''}</td>
                        <td style="border: 0.2px solid #666; padding: 4px; text-align: center;">${item.resultQty || ''}</td>
                        ${this.isBatch ? `<td style="border: 0.2px solid #666; padding: 4px; text-align: left;">${item.batchNo || ''}</td>` : ''}
                        <td style="border: 0.2px solid #666; padding: 4px; text-align: center;">${this.records? item.resultQty:''}</td>
                        <td style="border: 0.2px solid #666; padding: 4px; text-align: center;">${item.cgUnitName || ''}</td>
                      </tr>
                    `).join('')}
                    ${Array(Math.max(0, rowsPerPage - currentPageData.length)).fill().map(() => `
                      <tr>
                        <td style="border: 0.2px solid #666; padding: 4px; height: 24px;"></td>
                        <td style="border: 0.2px solid #666; padding: 4px;"></td>
                        <td style="border: 0.2px solid #666; padding: 4px;"></td>
                        ${this.isBatch ? `<td style="border: 0.2px solid #666; padding: 4px;"></td>` : ''}
                        <td style="border: 0.2px solid #666; padding: 4px;"></td>
                        <td style="border: 0.2px solid #666; padding: 4px;"></td>
                        <td style="border: 0.2px solid #666; padding: 4px;"></td>
                      </tr>
                    `).join('')}
                  </tbody>
                </table>

                <!-- 页码信息 -->
                <div style="text-align: center; margin-top: 20px; margin-bottom: 20px; font-size: 12px;">
                  第 ${pageNum + 1} 页 / 共 ${totalPages} 页
                </div>
              </div>
            `;
  
            // 等待内容渲染和图片加载
            await new Promise(resolve => setTimeout(resolve, 1000));
  
            // 确保所有图片加载完成
            const images = printContainer.getElementsByTagName('img');
            await Promise.all(Array.from(images).map(img => {
              if (img.complete) return Promise.resolve();
              return new Promise((resolve) => {
                img.onload = resolve;
                img.onerror = resolve;
              });
            }));
  
            // 使用html2canvas捕获内容
            const canvas = await html2canvas(printContainer, {
              scale: 2,
              useCORS: true,
              allowTaint: true,
              backgroundColor: '#ffffff',
              imageTimeout: 30000,
              logging: false,
              onclone: (clonedDoc) => {
                const clonedContent = clonedDoc.getElementById('print-container');
                if (clonedContent) {
                  clonedContent.style.position = 'static';
                }
              }
            });
  
            // 添加图片到PDF
            const imgWidth = 210; // A4 宽度 (mm)
            const pageHeight = 297; // A4 高度 (mm)
            const imgHeight = (canvas.height * imgWidth) / canvas.width;
            
            const imgData = canvas.toDataURL('image/jpeg', 1.0);
            
            // 如果不是第一页，添加新页面
            if (pageNum > 0) {
              pdf.addPage();
            }
            
            pdf.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight);
  
            // 清理当前页的打印容器
            document.body.removeChild(printContainer);
          }
  
          // 保存PDF
          pdf.save(`${this.headerInfo.billTitle || new Date().getTime()}.pdf`);
  
          loading.close();
          this.$message.success('PDF生成成功');
        } catch (error) {
          console.error('PDF生成错误:', error);
          this.$message.error('PDF生成失败：' + error.message);
        }
      },
    },
    // 组件销毁时清理二维码实例
    beforeDestroy() {
      if (this.qrCodeInstance) {
        this.qrCodeInstance.clear();
      }
    }
  }
  </script> 